<template>
  <div id="wangEditor">
    <div id="toolbar-container" style="z-index:20;" class="toolbar"></div>
    <div id="text-container" style="z-index:0;" class="text_container"></div>
  </div>
</template>
<script>
import wangeditor from 'wangeditor'
export default {
  data() {
    return {
      editor: '',
    }
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    isClear: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isClear(val) {
      // 触发清除文本域内容
      if (val) {
        this.editor.txt.clear()
        this.info_ = null
      }
    },
    value: function (value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value)
      }
    }
    //value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
  },
  mounted() {
    let _this = this
    _this.editor = new wangeditor('#toolbar-container', '#text-container')
    // 或者 const editor = new E( document.getElementById('div1') )
    //_this.editor.config.height = 500
    _this.editor.config.onchange = function (html) {
      _this.$emit("geteditor", html);
    }
    _this.editor.config.onchangeTimeout = 500
    _this.editor.config.uploadImgServer = '/resource/resources/upload'
    _this.editor.config.uploadImgMaxSize = 5 * 1024 * 1024 // 2M
    _this.editor.config.uploadImgMaxLength = 1
    _this.editor.config.uploadFileName = 'file'
    _this.editor.config.uploadImgHooks = {
      // 上传图片之前
      before: function () {
        // 可阻止图片上传
      },
      // 图片上传并返回了结果，图片插入已成功
      success: function (xhr) {
        console.log('success', xhr)
      },
      // 图片上传并返回了结果，但图片插入时出错了
      fail: function (xhr, editor, resData) {
        console.log('fail', resData)
      },
      // 上传图片出错，一般为 http 请求的错误
      error: function (xhr, editor, resData) {
        console.log('error', xhr, resData)
      },
      // 上传图片超时
      timeout: function (xhr) {
        console.log(xhr)
      },
      customInsert: function (insertImgFn, result) {
        console.log('customInsert', result)
        insertImgFn('/file/' + result.data.fileUrl)
      }
    }
    this.editor.create()
  },
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy()
    this.editor = null
  }
}
</script>
<style lang="scss" scope>
#wangEditor {
  height: 100%;
  width: 100%;
}
.toolbar {
  border: 1px solid #ccc;
}
.text_container {
  background: #f2f2f2;
  height: calc(100% - 45px);
  position: relative;
}
.w-e-toolbar {
  z-index: 300 !important;
}
.w-e-text-container {
  background-color: #f2f2f2 !important;
}
</style>


